using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Serialization;
using Awaiter;
using Nsb;
using Nsb.Classes;
using ThemeChain;
using jQueryApi;

namespace PlaySpace.Classes
{
    [IgnoreNamespace]
    public class LogsPage
    {
        private static readonly Dictionary<string, string> Headers = new Dictionary(
            "d", "date",
            "m", "message",
            "b", "browser",
            "u", "url"
            );

        private static string _logSite = "";

        [PreserveName, PreserveCase]
        public static void Page()
        {
            string lg = (string) Storage.GetSession(Spaces.LogSiteKey);
            if (lg != null)
            {
                if (lg == "root")
                    _logSite = Uri.Join("../../", ThemeBase.AppPath);
                else
                    _logSite = Uri.Join("../../spaces/", lg, ThemeBase.AppPath);
            }

            MakeTabBtn("#ErrorLogBtn", Uri.Join(_logSite, "db/logs/errors.txt")).Click();
            MakeTabBtn("#BuildLogBtn", Uri.Join(_logSite, "db/logs/build.txt"));
            MakeTabBtn("#EventLogBtn", Uri.Join(_logSite, "db/logs/events.txt"));
            MakeTabBtn("#MasterLogBtn", Uri.Join("/", ThemeBase.AppPath, "db/masterlogs/errors.txt"));

            if (lg != null)
                jQuery.Select("#CreatorLogs")
                    .AddClass("SpaceBtn")
                    .Click(
                        delegate
                        {
                            Storage.RemoveSession(Spaces.LogSiteKey);
                            ThemeYoshi.ReloadPage();
                        });
            else
                jQuery.Select("#CreatorLogs")
                    .Hide()
                    ;

            jQuery.Select("#SiteName")
                .Html(lg ?? ThemeBase.BaseName)
                ;
        }

        public static jQueryObject MakeTabBtn(string select, string path)
        {
            return jQuery.Select(select)
                .Closest(".Gig")
                .AddClass("LogTabBtn")
                .CSS(new Dictionary("background-color", "", "color", "", "border-color", "", "border-style", ""))
                .Click(delegate(jQueryEvent e)
                       {
                           jQuery.Select(".LogTabBtn").RemoveClass("Selected");
                           ShowLogAw(Await.AsyncAw, "#ErrorLogs", path);
                           jQuery.FromElement(e.Target).Closest(".Gig").AddClass("Selected");
                       })
                ;
        }

        public static void ShowLogAw(Await awp, string select, string path)
        {
            new Await()
                //.LoadText(select, path)
                .AddAw(FileBlobBase.RetrieveBlobStringAw, "", path, new Dictionary("allowEmpty", true))
                .HandleDl(Exceptions.BlobLoadError, delegate(Await aw)
                                                    {
                                                        jQuery.Select(select).Empty();
                                                        aw.Finish();
                                                    })
                .AddDx(
                    delegate(Await aw)
                    {
                        jQueryObject el = jQuery.Select(select);

                        string content = (string) aw.Result;
                        if (String.IsNullOrEmpty(content))
                        {
                            el.Empty();
                            return;
                        }

                        List<LogItem> list = (List<LogItem>) Json.Parse("[" + content + "]");
                        list.Reverse();

                        el
                            .Empty()
                            .Closest(".Gig").AddClass("LogView")
                            ;

                        jQueryObject box = jQuery.FromHtml("<div class='TableDiv'/>").AppendTo(el);
                        jQueryObject table = jQuery.FromHtml("<table/>").AppendTo(box);
                        jQueryObject head = jQuery.FromHtml("<thead/>").AppendTo(table);
                        jQueryObject body = jQuery.FromHtml("<tbody/>").AppendTo(table);

                        jQueryObject infobox = jQuery.FromHtml("<div class='InfoBox'/>")
                            .AppendTo(el)
                            .Html(path)
                            ;

                        jQuery.FromHtml("<img src='" + Uri.Img("Common/close20.png") + "' class='DelBtn'/>")
                            .AppendTo(infobox)
                            .Attribute("title", String.Format("delete {0} log", path))
                            .Click(delegate { DeleteLog(path); })
                            ;

                        jQueryObject tt = jQuery.FromHtml("<tr/>").AppendTo(head);
                        foreach (KeyValuePair<string, string> p in Headers)
                        {
                            jQuery.FromHtml("<th/>")
                                .AppendTo(tt)
                                .Html(p.Value)
                                ;
                        }

                        foreach (LogItem li in list)
                        {
                            jQueryObject tr = jQuery.FromHtml("<tr/>")
                                .AppendTo(body)
                                ;

                            foreach (KeyValuePair<string, string> p in Headers)
                            {
                                if (p.Key == "d")
                                {
                                    Date dd = new Date(li.t);
                                    jQuery.FromHtml("<td>")
                                        .AppendTo(tr)
                                        .Html(dd.Format("ddd MMM dd yyyy hh:mm:ss tt"))
                                        ;
                                }
                                else
                                    jQuery.FromHtml("<td>")
                                        .AppendTo(tr)
                                        .Html(Type.GetField(li, p.Key).ToString())
                                        ;
                            }
                        }
                    })
                .Commit(awp);
        }

        public static void DeleteLog(string path)
        {
            new Await()
                .AddAw(new Ask().OkCancelAw, ThemeYoshi.ForSure)
                .AddAw(DomElement.RequireResultAw, true)
                .AddAw(FileBlobBase.DeleteItemAw, "", path)
                .AddDx(delegate { ThemeYoshi.ReloadPage(); })
                .Commit();
        }
    }

    public class LogItem
    {
        public string b;
        public string d;
        public string e;
        public string i;
        public string m;
        public int t;
        public string u;
    }
}